package com.ly.mpayment.rest.up.tianzhong;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.net.URLDecoder;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
@Path("tianzhong")
public class TianZhongRest {
    Logger logger = Logger.getLogger(TianZhongRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @Path("callBack")
    @POST
    public String callBack(@RequestBody String data) {
        logger.info("tianzhong_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            JSONObject json = JSONObject.parseObject(data);

            UpOrder order = upOrderService.findById(json.getString("out_trade_no"));
            if(order == null){
                logger.info("orderNotify_not_found_order:"+json.getString("out_trade_no"));
            }
            if(json.getString("status").equals("1") && order != null  && order.getStatus() == Config.status[0]){
                order.setRemark(json.containsKey("voucher") ? json.getString("voucher") : "");
                RechargeRest.successUpOrder.add(order);
                return Config.success;
            }else if(order != null  && order.getStatus() == Config.status[0] && json.getString("status").equals("-1")){
                order.setRemark(json.getString("status"));
                RechargeRest.failtUpOrder.add(order);
                return Config.success;
            }
        }
        return "0";
    }


    /**
     * 订单提交
     * code	是(签名)	string	平台渠道商编号
     * phone	是(签名)	string	手机号
     * isp	是	int	手机号运营商 1移动 2联通 3电信
     * price	是	int	充值面值[50，100]
     * out_trade_no	是(签名)	string	渠道方订单号(长度50个字符以内)
     * notify_url	否	string	通知地址 异步有效 为空表示不通知
     * is_test	是	int	0正式 1测试 测试订单不会真实充值
     * sign	是	string	签名
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        UpOrder product = upOrderService.findOrderProduct(order.getUporderuuid());
        if (product != null) {
            JSONObject sb = new JSONObject();
            sb.put("code",shop.getAppId());
            //手机号运营商 1移动 2联通 3电信
            sb.put("isp", order.getOperators().equals("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e") ? "1" :
                    order.getOperators().equals("2ee16927-9f99-11e7-9dc0-fcaa1456507e") ? "2" :
                            order.getOperators().equals("2ee70961-9f99-11e7-9dc0-fcaa1456507e") ? "3" : "0");
            sb.put("phone",order.getUpphonenum());
            sb.put("price",order.getUpShopPro().getUpfacevalue());
            sb.put("out_trade_no",order.getUporderuuid());
            sb.put("product_id",product.getUpShopPro().getProductCode());
            sb.put("notify_url",shop.getOrderCallAddress());
            //code=xx&phone=xx&out_trade_no=xxx&key=xxx，对字符串进行md5签名，签名秘钥从商务获取
            sb.put("sign",MD5.md5("code="+shop.getAppId()+"&phone="+order.getUpphonenum()+"&out_trade_no="+order.getUporderuuid()+"&key="+shop.getUpkey()));
            String result = HttpClient.post(shop.getOrderCommitAddress(), sb.toString());
            logger.info("committianzhong:"+result);
            if(!StringUtils.isBlank(result)){
                net.sf.json.JSONObject json = JsonUtils.getJSONOBJCT().fromObject(result);
                if(json.containsKey("status") && json.getString("status").equals("1")){
                    upOrderService.updateUpOrderMsg(order, json.getJSONObject("data").containsKey("trade_no") ? json.getJSONObject("data").getString("trade_no") : "",
                            json.getString("msg"));
                }else if(json.containsKey("status") && json.getString("status").equals("0")){
                    order.setRemark( json.getString("msg"));
                    RechargeRest.failtUpOrder.add(order);
                }
            } else {
                upOrderService.updateUpOrderMsg(order, "","提单失败人工核对:"+result);
            }
        }else{
            logger.info("commitLeXiang error not found product" + order.getUporderuuid());
        }
    }

    /**
     * 订单查询
     *
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject data = new JSONObject();
        data.put("code", shopInfo.getAppId());
        data.put("out_trade_no",upOrder.getUporderuuid());
        data.put("sign",MD5.md5("code="+shopInfo.getAppId()+"&out_trade_no="+upOrder.getUporderuuid()+"&key="+shopInfo.getUpkey()));
        String result = HttpClient.post(shopInfo.getOrderStatusAddress(), data.toString());
        logger.info("tianzhong_orderQuery:"+result);
        if(result != null){
            net.sf.json.JSONObject json = JsonUtils.getJSONOBJCT().fromObject(result);
            if(json.containsKey("status") && json.getString("status").equals(Config.success)){
                upOrder = upOrderService.findById(json.getJSONObject("data").getString("out_trade_no"));
                //0 失败，1 成功，4失败
                if(upOrder != null && json.getJSONObject("data").getString("status").equals("1") && upOrder.getStatus() == Config.status[0]){
                    upOrder.setRemark(json.getJSONObject("data").containsKey("voucher") ?
                            json.getJSONObject("data").getString("voucher") : json.getString("msg"));
                    RechargeRest.successUpOrder.add(upOrder);
                }else if( (json.getJSONObject("data").getString("status").equals("-1")) && upOrder != null && upOrder.getStatus() == Config.status[0]){
                    upOrder.setRemark( json.getString("msg"));
                    RechargeRest.failtUpOrder.add(upOrder);
                }
            }
        }else{
            logger.info("tianzhong order failt:"+upOrder.getUpphonenum());
        }
    }

}
